//
//  YCShareUI.m
//  YCVillageDoctor
//
//  Created by itclimb on 2017/7/13.
//  Copyright © 2017年 zhangxiaoliang. All rights reserved.
//

#import "YCShareUI.h"

#define kScale SCREEN_WIDTH/375
#define kInsetLength 5 * kScale
#define kMargin 8

@interface YCShareUI ()<UICollectionViewDelegate,UICollectionViewDataSource>
//分享面板数据
@property(nonatomic, strong) NSMutableArray<NSDictionary *> *introDatas;
//取消按钮
@property(nonatomic, strong) UIButton *cancelButton;

@property(nonatomic, copy) ShareUIDismissBlock block;

@property(nonatomic, copy) ShareUIDidSelectBlock selectBlock;

@end

static NSString *kIdentifier = @"kCell";

@implementation YCShareUI
{
    CGFloat _collectionHeight;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithHexString:@"#e7e7e7"];
        //Title
        UILabel *title = [[UILabel alloc] init];
        title.text = @"分享";
        title.textColor = [UIColor colorWithHexString:@"333333"];
        title.font = [UIFont systemFontOfSize:15.0];
        title.backgroundColor = [UIColor clearColor];
        [self addSubview:title];
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self);
            make.top.mas_equalTo(self).offset(kMargin);
            make.height.mas_equalTo(20 * kScale);
        }];
        
        _height += kMargin + 20 * kScale;
        
        //Line
        UIView *line = [UIView new];
        line.backgroundColor = [UIColor whiteColor];
        [self addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(title.mas_bottom).offset(kMargin);
            make.left.mas_equalTo(self).offset(12);
            make.right.mas_equalTo(self).offset(-12);
            make.height.mas_equalTo(1);
            
        }];
        _height += kMargin + 1;
        
        //CollectionView
        CGFloat collectionCellW = 70;
        CGFloat collectionCellH = 70;
        _collectionHeight = 2 * (collectionCellH * kScale) + 2 * kInsetLength + 10;
        if (self.introDatas.count < 5) {
            _collectionHeight -= (collectionCellH * kScale + kMargin);
        }
        PopCollectionViewLayout *flowLayout = [[PopCollectionViewLayout alloc] init];
        flowLayout.minimumLineSpacing = kMargin * kScale;
        flowLayout.minimumInteritemSpacing = kMargin * kScale;
        flowLayout.itemSize = CGSizeMake(collectionCellW * kScale, collectionCellH * kScale);
        flowLayout.sectionInset = UIEdgeInsetsMake(kInsetLength, kInsetLength, kInsetLength, kInsetLength);
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.pagingEnabled = YES;
        [self addSubview:collectionView];
        [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(line.mas_bottom).offset(kMargin);
            make.left.mas_equalTo(12);
            make.right.mas_equalTo(-12);
            make.height.mas_equalTo(_collectionHeight);
            
        }];
        [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:kIdentifier];
        _height += _collectionHeight + kMargin;
        
        //Cancel button
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.backgroundColor = [UIColor whiteColor];
        _cancelButton.layer.masksToBounds = YES;
        _cancelButton.layer.cornerRadius = 3;
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton setTitleColor:[UIColor colorWithHexString:@"333333"] forState:UIControlStateNormal];
        [self addSubview:_cancelButton];
        [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(collectionView.mas_bottom).offset(kMargin);
            make.left.mas_equalTo(self).offset(12);
            make.right.mas_equalTo(self).offset(-12);
            make.height.mas_equalTo(40 * kScale);
        }];
        [_cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _height += kMargin + 40 * kScale;
        
    }
    return self;
}

//MARK: - 设置分享平台数据
- (void)setSharePlatform:(YCSharePlatform)sharePlatform{
    _sharePlatform = sharePlatform;
    [self setSharePlatformData];
}

#pragma mark - CollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.introDatas.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kIdentifier forIndexPath:indexPath];
    
    UIView *cellView = [UIView new];
    [cell addSubview:cellView];
    [cellView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(cell);
    }];
    
    NSString *imageName = self.introDatas[indexPath.row][@"imageName"];
    UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
    [cellView addSubview:icon];
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(cellView);
        make.top.mas_equalTo(cellView);
        make.width.height.mas_equalTo(40 * kScale);
    }];
    
    UILabel *introLabel = [UILabel new];
    introLabel.text = self.introDatas[indexPath.row][@"text"];
    introLabel.font = [UIFont systemFontOfSize:13.0];
    introLabel.textColor = [UIColor colorWithHexString:@"999999"];
    [cellView addSubview:introLabel];
    [introLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(cellView);
        make.top.mas_equalTo(icon.mas_bottom).offset(12 * kScale);
    }];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.block) {
        self.block();
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.selectBlock) {
            self.selectBlock(indexPath, self.introDatas);
        }
    });
}

//MARK: - 取消按钮点击事件
- (void)cancelButtonClick:(id)sender{
    if (self.block) {
        self.block();
    }
}

#pragma mark - lazy load

- (NSMutableArray<NSDictionary *> *)introDatas{
    if (!_introDatas) {
        _introDatas = [NSMutableArray array];
    }
    return _introDatas;
}

- (void)setSharePlatformData{
    
    if (_sharePlatform & YCSharePlatformWechatSession) {
        NSDictionary *dic = @{
                              @"text":@"微信好友",
                              @"imageName":@"share0",
                              @"platform":@"UMSocialPlatformType_WechatSession"
                              };
        [self.introDatas addObject:dic];
    }
    
    if (_sharePlatform & YCSharePlatformWechatTimeLine){
        NSDictionary *dic = @{
                              @"text":@"微信朋友圈",
                              @"imageName":@"share1",
                              @"platform":@"UMSocialPlatformType_WechatTimeLine"
                              };
        [self.introDatas addObject:dic];
    }
    
    if (_sharePlatform & YCSharePlatformWechatFavorite){
        NSDictionary *dic = @{
                              @"text":@"微信收藏",
                              @"imageName":@"share2",
                              @"platform":@"UMSocialPlatformType_WechatFavorite"
                              };
        [self.introDatas addObject:dic];
    }
    
    if (_sharePlatform & YCSharePlatformQQ){
        NSDictionary *dic = @{
                              @"text":@"QQ",
                              @"imageName":@"share3",
                              @"platform":@"UMSocialPlatformType_QQ"
                              };
        [self.introDatas addObject:dic];
    }
    
    if (_sharePlatform & YCSharePlatformQzone){
        NSDictionary *dic = @{
                              @"text":@"QQ空间",
                              @"imageName":@"share4",
                              @"platform":@"UMSocialPlatformType_Qzone"
                              };
        [self.introDatas addObject:dic];
    }
    
    if (_sharePlatform & YCSharePlatformSina){
        NSDictionary *dic = @{
                              @"text":@"新浪微博",
                              @"imageName":@"share5",
                              @"platform":@"UMSocialPlatformType_Sina"
                              };
        [self.introDatas addObject:dic];
    }
}

- (void)setShareUIDismissBlock:(ShareUIDismissBlock)block{
    _block = block;
}

- (void)setShareUIDidSelectBlock:(ShareUIDidSelectBlock)selectBlock{
    _selectBlock = selectBlock;
}


@end


@implementation PopCollectionViewLayout
{
    int _row;
    int _col;
    CGFloat _itemSpacing;
    CGFloat _lineSpacing;
    long    _pageNumber;
}


- (instancetype)init {
    self = [super init];
    if (self){
        self.attributes = [NSMutableArray new];
    }
    return self;
}


- (void)prepareLayout {
    [super prepareLayout];
    
    CGFloat itemWidth  = self.itemSize.width;
    CGFloat itemHeight = self.itemSize.height;
    
    CGFloat width  = self.collectionView.frame.size.width;
    CGFloat height = self.collectionView.frame.size.height;
    
    CGFloat contentWidth = (width - self.sectionInset.left - self.sectionInset.right);
    
    // 如果列数大于 2 行
    if (contentWidth >= (2 * itemWidth + self.minimumInteritemSpacing)) {
        
        NSInteger m = (contentWidth - itemWidth) / (itemWidth + self.minimumInteritemSpacing);
        
        _col = (int)(m + 1);
        
        NSInteger n = (NSInteger)(contentWidth - itemWidth) % (NSInteger)(itemWidth + self.minimumInteritemSpacing);
        
        if (n > 0) {
            
            double offset = ((contentWidth - itemWidth) - m * (itemWidth + self.minimumInteritemSpacing)) / m;
            
            _itemSpacing = self.minimumInteritemSpacing + offset;
            
        }else if (n == 0) {
            _itemSpacing = self.minimumInteritemSpacing;
        }
        // 如果列数为 1 行
    }else {
        _col = 1;  // 注意不为0 10.0后模拟器会崩，真机没问题
        _itemSpacing = 0;
    }
    
    CGFloat contentHeight = (height - self.sectionInset.top - self.sectionInset.bottom);
    
    // 如果行数大于 2 行
    if (contentHeight >= (2 * itemHeight + self.minimumLineSpacing)) {
        
        NSInteger m = (contentHeight - itemHeight) / (itemHeight + self.minimumLineSpacing);
        
        _row = (int)(m + 1);
        
        NSInteger n = (NSInteger)(contentHeight - itemHeight) % (NSInteger)(itemHeight + self.minimumLineSpacing);
        
        if (n > 0) {
            
            double offset = ((contentHeight - itemHeight) - m * (itemHeight + self.minimumLineSpacing)) / m;
            
            _lineSpacing = self.minimumLineSpacing + offset;
            
        }else if (n == 0) {
            
            _lineSpacing = self.minimumInteritemSpacing;
        }
        // 如果行数数为 1 行
    }else {
        _row = 1; // 注意不为0 10.0后模拟器会崩，真机没问题
        _lineSpacing = 0;
    }
    
    NSInteger itemNumber = 0;
    
    itemNumber = itemNumber + (NSInteger)[self.collectionView numberOfItemsInSection:0];
    
    // 注意不为0 10.0后模拟器会崩，真机没问题
    _pageNumber = itemNumber == 1 ? 1 : (itemNumber - 1) / (_row * _col) + 1;
}

#pragma mark - collectionView 的整体滚动区域
- (CGSize)collectionViewContentSize {
    return CGSizeMake(self.collectionView.bounds.size.width * _pageNumber, self.collectionView.bounds.size.height);
}


- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewLayoutAttributes * attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    CGRect frame;
    frame.size = self.itemSize;
    long number = _row * _col;
    long m = 0;
    long p = 0;
    if (indexPath.item >= number) {
        
        p = indexPath.item / number;
        m = (indexPath.item % number) / _col;
    }else {
        
        m = indexPath.item / _col;
    }
    
    long n = indexPath.item % _col;
    frame.origin = CGPointMake(n * self.itemSize.width + n * _itemSpacing + self.sectionInset.left + (indexPath.section + p) * self.collectionView.frame.size.width, m * self.itemSize.height + m * _lineSpacing + self.sectionInset.top);
    
    attribute.frame = frame;
    return attribute;
}


- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    
    NSMutableArray * tmpAttributes = [NSMutableArray new];
    for (int j = 0; j < self.collectionView.numberOfSections; j ++) {
        
        NSInteger count = [self.collectionView numberOfItemsInSection:j];
        for (NSInteger i = 0; i < count; i++) {
            
            NSIndexPath * indexPath = [NSIndexPath indexPathForItem:i inSection:j];
            [tmpAttributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
        }
    }
    self.attributes = tmpAttributes;
    return self.attributes;
}


//MARK: - 是否需要重新布局
- (BOOL)ShouldinvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return NO;
}

@end
